/**
 * 文件名：WidgetController.java
 *
 * 版本信息：v1.0
 * 日期：2013-6-22
 * Copyright  Corporation 2013 
 * 版权所有
 *
 */

package com.foreveross.bsl.mam.model.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.common.utils.bean.FileUtils;
import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.AppVersionApplication;
import com.foreveross.bsl.mam.app.application.AppVersionWidgetVersionApplication;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionWidgetVersionVo;
import com.foreveross.bsl.mam.model.application.AttachmentApplication;
import com.foreveross.bsl.mam.model.application.WidgetApplication;
import com.foreveross.bsl.mam.model.application.WidgetCategoryApplication;
import com.foreveross.bsl.mam.model.application.WidgetSnapshotApplication;
import com.foreveross.bsl.mam.model.application.WidgetVersionApplication;
import com.foreveross.bsl.mam.model.application.vo.AttachmentVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetCategoryVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetSnapshotVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVO;
import com.foreveross.bsl.mam.model.application.vo.WidgetVersionVO;

/**
 * 此类描述的是：模块业务逻辑控制器
 * 
 * @author: panhm@foreveross.com
 * @version: 2013-6-22 下午4:49:42
 */

@Controller
@RequestMapping(value = "/mam/widgetVersion")
public class WidgetVersioinController extends WidgetBaseController {
	private Log log = LogFactory.getLog(WidgetVersioinController.class);

	@Inject
	private WidgetApplication widgetApplication;

	@Inject
	private AttachmentApplication attachmentApplication;

	@Inject
	private WidgetVersionApplication widgetVersionApplication;

	@Inject
	private WidgetCategoryApplication widgetCategoryApplication;

	@Inject
	private AppVersionWidgetVersionApplication appVersionWidgetVersionApplication;

	@Inject
	private AppMainApplication appMainApplication;

	@Inject
	private WidgetSnapshotApplication widgetSnapshotApplication;

	@Inject
	private AppVersionApplication appVersionApplication;

	/**
	 * 此方法描述的是：进入模块版本添加页面
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:41
	 */

	@RequestMapping("/add-view")
	public String versionAddView(@RequestParam("widgetID") String widgetID, Model model) {

		WidgetVO widgetVO = widgetApplication.getEntity(widgetID);
		List<WidgetVersionVO> list = widgetVersionApplication.findByWidgetId(widgetID);
		if (list != null && list.size() > 0) {
			WidgetVersionVO versionVO = list.get(0);
			model.addAttribute("versionVO", versionVO);
		}
		model.addAttribute("widgetVO", widgetVO);
		return "model/version-add";
	}

	/**
	 * 此方法描述的是：添加模块版本信息
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:41
	 */

	@RequestMapping("/add")
	@ResponseBody
	public Map<String, String> versionAdd(WidgetVersionVO versionVO, HttpServletRequest request) {

		Map<String, String> result = new HashMap<String, String>();
		versionVO.setAvailable(1);
		Date creattime = new Date();
		versionVO.setCreated_at(creattime);
		versionVO.setModified_at(creattime);
		WidgetVersionVO widgetvo = this.widgetVersionApplication.widgetVersion(versionVO.getWidget_id(), versionVO.getVersion());
		if (widgetvo != null) {// 版本已经存在
			result.put("result", "success");
			result.put("status", "1");
			return result;
		}
		Map<String, Object> jsonConfig = new HashMap<String, Object>();
		jsonConfig.put("version", versionVO.getVersion());
		jsonConfig.put("releaseNote", versionVO.getRelease_not());
		try {
			AttachmentVO vo = attachmentApplication.getEntity(versionVO.getBoundle());
			String filePath = FileUtils.modifyConfigFile(vo.getLocalFilename(), jsonConfig);
			// tfs api
			FileStorageFactory f = FileStorageFactory.getInstance();
			FileStorage fs = f.getFileStorage();
			String fileid = fs.saveFile(filePath, null, null);
			vo.setId(fileid);
			vo.setLocalFilename(fileid);
			this.attachmentApplication.saveEntity(vo);
			versionVO.setBoundle(vo.getId());
			widgetVersionApplication.saveEntity(versionVO);
			result.put("widgetid", versionVO.getWidget_id());
			result.put("result", "success");
			result.put("status", "0");
		} catch (Exception e) {
			log.error("[versionAdd]", e);
			result.put("result", "error");
		}
		return result;
	}

	/**
	 * 此方法描述的是：进入模块版本详情页面
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:41
	 */

	@RequestMapping("/view")
	public String versionView(@RequestParam("id") String id, Model model) {
		WidgetVersionVO versionVO = widgetVersionApplication.getEntity(id);
		WidgetVO widgetVO = widgetApplication.getEntity(versionVO
				.getWidget_id());
		WidgetCategoryVO categoryVO = widgetCategoryApplication
				.getEntity(widgetVO.getCategory_id());
		model.addAttribute("categoryVO", categoryVO);
		model.addAttribute("widgetVO", widgetVO);
		model.addAttribute("versionVO", versionVO);
		List<AppVersionWidgetVersionVo> listAppWidget = appVersionWidgetVersionApplication
				.getListByWidget(versionVO.getWidget_id(),
						versionVO.getVersion());
		// List<AppMainVo> appList = new ArrayList<AppMainVo>();
		// Map<String, String> mapFilter = new HashMap<String, String>();
		List<Map<String, Object>> appRelList = new ArrayList<Map<String, Object>>();
		if (listAppWidget != null && listAppWidget.size() > 0) {
			List<AppVersionVo> appVersionList = null;
			AppMainVo appMain = null;
			Map<String, Object> appMap = null;
			for (AppVersionWidgetVersionVo av : listAppWidget) {
				appVersionList = appVersionApplication
						.getAppVersionByPlatformAndVersion(av.getAppId(),
								av.getAppVersion(), av.getPlatform());
				appMap = new HashMap<String, Object>();
				if (null != appVersionList && !appVersionList.isEmpty()) {
					appMap.put("appVersion", appVersionList.get(0));
				} else {
					continue;
				}
				appMain = appMainApplication.getEntity(av.getAppId());
				appMap.put("app", appMain);
				appRelList.add(appMap);
				// String filterKey = av.getAppId()+av.getAppVersion();
				// if (app != null && !mapFilter.containsKey(filterKey)) {
				// mapFilter.put(filterKey, filterKey);
				// app.setDiscription(av.getAppVersion());
				// appList.add(app);
				// }
			}
		}
		List<WidgetSnapshotVO> listSnapshot = widgetSnapshotApplication
				.findByVersionId(id);
		model.addAttribute("listSnapshot", listSnapshot);
		model.addAttribute("appList", appRelList);
		return "model/version-view";
	}

	/**
	 * 此方法描述的是：进入更新版本页面
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:41
	 */
	@RequestMapping("/update-view/{id}")
	public String ajaxVersion(@PathVariable String id, Model model) {
		WidgetVersionVO wversion = widgetVersionApplication.getEntity(id);
		WidgetVO widgetVO = widgetApplication
				.getEntity(wversion.getWidget_id());
		model.addAttribute("wversion", wversion);
		model.addAttribute("widgetVO", widgetVO);
		return "model/version-update";
	}

	/**
	 * 此方法描述的是：更新模块版本信息
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-22 下午4:55:41
	 */

	@RequestMapping("/update")
	@ResponseBody
	public Map<String, String> update(WidgetVersionVO versionVO) {
		Map<String, String> result = new HashMap<String, String>();

		// Map<String, Object> jsonConfig = new HashMap<String, Object>();
		// jsonConfig.put("version", versionVO.getVersion());
		// jsonConfig.put("build", versionVO.getBuild());
		// jsonConfig.put("releaseNote", versionVO.getRelease_not());
		// jsonConfig.put("hidden", versionVO.isHidden());
		try {
			// AttachmentVO vo = attachmentApplication.getEntity(versionVO
			// .getBoundle());
			// String filePath =
			// FileUtils.modifyConfigFile(vo.getLocalFilename(),
			// jsonConfig.toString());
			// FileStorageFactory f = FileStorageFactory.getInstance();
			// FileStorage fs = f.getFileStorage();
			// String fileid = fs.saveFile(filePath, null, null);
			// vo.setId(fileid);
			// vo.setLocalFilename(fileid);
			// attachmentApplication.saveEntity(vo);
			// versionVO.setBoundle(vo.getId());
			widgetVersionApplication.updateEntity(versionVO.getId(), versionVO);
			result.put("id", versionVO.getId());
			result.put("result", "success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("[update]", e);
			result.put("result", "error");
		}
		return result;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(String id) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			widgetVersionApplication.deleteEntity(id);
			result.put("result", "success");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("[update]", e);
			result.put("result", "error");
		}
		return result;
	}

	@RequestMapping("/showCloneView/{id}")
	public String showCloneView(@PathVariable("id") String id, Model model) {

		WidgetVersionVO versionVO = widgetVersionApplication.getEntity(id);
		model.addAttribute("versionVO", versionVO);
		return "model/clone-view";
	}

	@ResponseBody
	@RequestMapping("/cloneAdd/{id}")
	public Map<String, String> cloneAdd(@PathVariable("id") String id,
			WidgetVersionVO versionVO) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			// 获取克隆信息
			WidgetVersionVO wVersion = widgetVersionApplication.getEntity(id);
			if (wVersion != null) {
				Date date = new Date();
				versionVO.setId(null);
				versionVO.setAvailable(1);
				versionVO.setCreated_at(date);
				versionVO.setModified_at(date);
				versionVO.setWidget_id(wVersion.getWidget_id());

				WidgetVersionVO widgetvo = widgetVersionApplication
						.widgetVersion(versionVO.getWidget_id(),
								versionVO.getVersion());
				if (widgetvo != null) {// 版本已经存在
					result.put("result", "success");
					result.put("status", "1");
					return result;
				}

				WidgetVersionVO saveVersion = widgetVersionApplication
						.saveEntity(versionVO);
				// 克隆快照
				List<WidgetSnapshotVO> listSnapShot = widgetSnapshotApplication
						.findByVersionId(wVersion.getId());
				if (listSnapShot != null) {
					for (WidgetSnapshotVO snashotVo : listSnapShot) {
						WidgetSnapshotVO entity = new WidgetSnapshotVO();
						entity.setSnapshot(snashotVo.getSnapshot());
						entity.setVersionId(saveVersion.getId());
						entity.setModified_at(date);
						entity.setCreated_at(date);
						entity.setAvailable(1);
						widgetSnapshotApplication.saveEntity(entity);
					}
				}

				result.put("result", "success");
				result.put("status", "0");
			}
		} catch (Exception e) {
			log.error("[cloneAdd]", e);
			result.put("result", "error");
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/{identifier}/{version}")
	public Map<String, String> identifierVersion(
			@PathVariable("identifier") String identifier,
			@PathVariable("version") String version) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			// 获取克隆信息
			WidgetVersionVO wVersion = widgetVersionApplication.checkIdentity(
					identifier, version);
			if (wVersion != null) {
				result.put("result", "true");
			} else {
				result.put("result", "false");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("[identifierVersion]", e);
			result.put("result", "error");
		}
		return result;
	}
}
